<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="true"
    :title="`选择标签`"
    width="400"
    @close="resetForm(ruleFormRef)"
    destroy-on-close
  >
    <el-form
      ref="ruleFormRef"
      style=""
      :model="ruleForm"
      status-icon
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item
        label=""
        :rules="[
          {
            required: true,
            message: '请选择标签',
            trigger: ['blur', 'change'],
          },
        ]"
        prop="selectTag"
      >
        <el-select
          v-model="ruleForm.selectTag"
          multiple
          collapse-tags
          collapse-tags-tooltip
          placeholder="请选择标签"
          style=""
        >
          <el-option
            v-for="item in tagList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" @click="confirm(ruleFormRef)">确 定</el-button>
      <el-button type="warning" @click="resetForm(ruleFormRef)"
        >取 消</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, watch, nextTick, reactive } from 'vue'
import useNoteStore from '@/stores/note.js'
import { httpUpdateNote } from '@/api/note'
import { storeToRefs } from 'pinia'

const noteStore = useNoteStore()
const { tagList } = storeToRefs(noteStore)
const visible = defineModel('visible')
const ruleFormRef = ref()
const props = defineProps({
  rowData: {
    type: Object,
    default: () => {},
  },
  edit: {
    type: Boolean,
    default: false,
  },
  callback: {
    type: Function,
    default: () => {},
  },
})
const ruleForm = reactive({
  selectTag: undefined,
})
watch(
  () => visible.value,
  () => {
    nextTick(() => {
      if (props.rowData.label.length) {
        ruleForm.selectTag = props.rowData.label.map((item) => item.label_id)
      } else {
        ruleForm.selectTag = undefined
      }
    })
  },
)
const confirm = async (ruleFormRef) => {
  if (!ruleFormRef) return
  await ruleFormRef.validate(async (valid, fields) => {
    if (valid) {
      const res = await httpUpdateNote({
        fd_id: props.rowData.id,
        title: props.rowData.title,
        content: props.rowData.content,
        label_id_list: ruleForm.selectTag,
      })
      if (res) {
        if (props.edit) {
          props.callback()
        } else {
          noteStore.getList()
        }
        visible.value = false
      }
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  visible.value = false
  ruleForm.selectTag = undefined
}
</script>
